package org.mat.framework.service.context;

import org.apache.commons.lang3.StringUtils;
import org.mat.framework.core.context.RequestContextConstants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.Map;

/**
 * @ClassName: FeignClientRequestInterceptor
 * @Date: 2021/8/17
 * @author: sunxinhe
 * @Version: 1.0
 * @Description: TODO
 */
@Slf4j
public class RequestContextFeignClientInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                String values = request.getHeader(name);
                requestTemplate.header(name, values);
            }
        }
        String traceId = MDC.get(RequestContextConstants.TRACE_ID_KEY_FOR_MDC);
        log.info("set traceId for feign request: url = {}, traceId = {} ", requestTemplate.url(), traceId);
        requestTemplate.header(RequestContextConstants.TRACE_ID_KEY_FOR_HTTP_HEADER, traceId);

//        // 传递用户信息请求头，防止丢失
//        String userId = request.getHeader(SecurityConstants.DETAILS_USER_ID);
//        if (StringUtils.isNotEmpty(userId))
//        {
//            requestTemplate.header(SecurityConstants.DETAILS_USER_ID, userId);
//        }
//        String userKey = request.getHeader(SecurityConstants.USER_KEY);
//        if (StringUtils.isNotEmpty(userKey))
//        {
//            requestTemplate.header(SecurityConstants.USER_KEY, userKey);
//        }
//        String userName = request.getHeader(SecurityConstants.DETAILS_USERNAME);
//        if (StringUtils.isNotEmpty(userName))
//        {
//            requestTemplate.header(SecurityConstants.DETAILS_USERNAME, userName);
//        }
//        String authentication = request.getHeader(SecurityConstants.AUTHORIZATION_HEADER);
//        if (StringUtils.isNotEmpty(authentication))
//        {
//            requestTemplate.header(SecurityConstants.AUTHORIZATION_HEADER, authentication);
//        }
    }

}
